package com.ellfors.module_first.picture_selector;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class PictureSelectorUtils {
    public static File uriToFile(Context context, Uri uri) {
        File file = null;
        String filePath = getFilePathFromUri(context, uri);
        if (filePath != null) {
            file = new File(filePath);
        } else {
            // 处理不能直接获取路径的情况，将文件复制到临时目录
            try {
                file = createFileFromUri(context, uri);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    // 使用 ContentResolver 获取文件路径
    private static String getFilePathFromUri(Context context, Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            if (cursor.moveToFirst()) {
                String filePath = cursor.getString(column_index);
                cursor.close();
                return filePath;
            }
            cursor.close();
        }
        return null;
    }

    // 处理无法直接获取路径的 URI，将其内容复制到一个临时文件中
    private static File createFileFromUri(Context context, Uri uri) throws IOException {
        InputStream inputStream = context.getContentResolver().openInputStream(uri);
        File tempFile = File.createTempFile("temp", null, context.getCacheDir());
        if (inputStream != null) {
            try (OutputStream outputStream = new FileOutputStream(tempFile)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            } finally {
                inputStream.close();
            }
        }
        return tempFile;
    }
}